package com.example.myapplication

import android.content.Context
import java.io.File

/**
 * @author Quinn
 * @date 2022/9/8
 * @Desc
 */
class StoreManager {

    private lateinit var storePath: String

    fun init(context: Context) {
        storePath = context.filesDir.absolutePath
    }

    /**
     * store encrypted data
     */
    fun diskCacheStore(
        target: List<String>,
        userId: String
    ) = targetStore(userId).printWriter().use { _outPrint ->
        // first line web2 password
        // second line web3 password
        // third line web3 mnemonic
        // forth line web3 keystore file name
        target.forEach {
            _outPrint.println(it)
        }
    }


    /**
     * generate files to store encrypted data
     */
    private fun targetStore(userId: String, tip: String = "") =
        generateStoreFile(userId, tip).apply {
            this.parentFile?.mkdirs()
            this.takeUnless { it.exists() }?.createNewFile()
        }

    /**
     * generate store file
     */
    private fun generateStoreFile(userId: String, tip: String = "") = File(
        keystoreFileParent(userId).absolutePath
                + File.separator
                + MD5Utils.encode(MD5Utils.encode(userId))
                + tip
    )

    fun revert(userId: String) {
        try {
            takeIf { targetStore(userId).renameTo(generateStoreFile(userId, "-bak")) }
                ?.takeIf { targetStore(userId, "-org").renameTo(generateStoreFile(userId)) }
                ?.takeIf { targetStore(userId, "-bak").delete() }
        } catch (e: Exception) {
            // if an exception occurs restore the backup file
            targetStore(userId, "-bak").renameTo(generateStoreFile(userId))
        }
    }

    fun reset(userId: String) {
        targetStore(userId).renameTo(generateStoreFile(userId, "-org"))
    }

    fun hasOrgStore(userId: String): Boolean = targetStore(userId, "-org").exists()

    /**
     * keystore storage path
     */
    fun keystoreFileParent(userId: String) =
        File(storePath + File.separator + MD5Utils.encode(userId)).apply { mkdirs() }

    fun keystoreFilePath(userId: String, keystoreName: String): String {
        return keystoreFileParent(userId).absolutePath + File.separator + keystoreName
    }

    fun loadStore(userId: String): List<String> {
        return targetStore(userId).readLines()
    }
}

enum class WalletState {
    RESETTING,
    NORMAL
}